package com.google.ant.extensions.types;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.tools.ant.Project;

public class DependencyHelper {
    private final Collection<Dependency> dependencies;
    private final Project project;

    public DependencyHelper(final Project proj, final Collection<Dependency> deps) {
        this.dependencies = deps;
        this.project = proj;
    }

    private void versionConflict(Dependency target, StringBuffer buffer) {
        for (Dependency d : this.dependencies) {
            if (target.isSameArtifact(d) && !target.isSameVersion(d)) {
                buffer.append("        |_ ");
                buffer.append(target.toString());
                buffer.append(" -- ");
                buffer.append(d.toString());
                buffer.append("\n");
            }
        }
    }

    private void checkDuplicateAndConflicts(Dependency dependency, Collection<Dependency> ds) {
        StringBuffer duplicates = new StringBuffer();
        StringBuffer conflicts = new StringBuffer();

        for (Dependency d : ds) {
            if (this.dependencies.contains(d)) {
                duplicates.append("        |_ ");
                duplicates.append(d.toString());
                duplicates.append("\n");
            }
            versionConflict(d, conflicts);
        }
        
        if (duplicates.length() > 0) {
            System.out.println("Found duplicate dependencies through: " + dependency);
            System.out.println(duplicates.toString());
        }

        if (conflicts.length() > 0) {
            System.out.println("Found conflict dependencies through: " + dependency);
            System.out.println(conflicts);
        }
    }

    public Collection<Dependency> getAllDependencies() {
        DependencyManager depMan = new DependencyManager(this.project);

        Set<Dependency> results = new HashSet<Dependency>();
        results.addAll(this.dependencies);

        for (Dependency dependency : this.dependencies) {
            Collection<Dependency> d = depMan.getDependencies(dependency);
            checkDuplicateAndConflicts(dependency, d);
            results.addAll(d);
        }
        return results;
    }
}